/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using Oceanside;
using Oceanside.Usb;
namespace Oceanside
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Window and GUI
        private static Encoding _enc;

        private MainWindow()
        {
            InitializeComponent();
            _enc = Encoding.GetEncoding("us-ascii",
                              new EncoderExceptionFallback(),
                              new DecoderExceptionFallback());
        }

        static bool isFirstGet = true;
        static MainWindow singleton = null;
        public static MainWindow Singleton
        {
            get
            {
                if (singleton == null)
                {
                    singleton = new MainWindow();
                    if (isFirstGet && Constants.IsCustomBrandedLicense)
                    {
                        if (App.CorporateResourceDictionary != null)
                        {
                            singleton.Resources.MergedDictionaries.Clear();
                            singleton.Resources.MergedDictionaries.Add(App.CorporateResourceDictionary);
                            singleton.UpdateLayout();
                        }
                    }
                }
                return singleton;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        public static void AssignDataContext(object o)
        {
            singleton.DataContext = o;
        }

        public static TabControl MainTabControl()
        {
            return singleton.mainTabControl;
        }

        public static Oceanside.CircularProgressBar ProgressCircle
        {
            get
            {
                return singleton.progressCircle;
            }
        }

        #endregion Window and GUI

        #region USB Event Handling and Transactions

        /// <summary>
        /// The handle to the usb subsystem.
        /// </summary>
        private UsbHidPort magSwipeUSB;
        private UsbHidPort coinUSB;
        public UsbHidPort CoinUSB
        {
            get { return coinUSB; }
            set { coinUSB = value; }
        }

        /// <summary>
        /// This event fires when the USB lib finds the device that
        /// we are looking for.  It must be used no matter what
        /// because the LIB will not send data if this is not
        /// present.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mag_usb_OnSpecifiedDeviceArrived(object sender, EventArgs e)
        {

        }
        private void coin_usb_OnSpecifiedDeviceArrived(object sender, EventArgs e)
        {

        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            try
            {
                singleton.magSwipeUSB = new UsbHidPort();
                singleton.magSwipeUSB.ProductId = 1280;
                singleton.magSwipeUSB.VendorId = 2765;
                singleton.magSwipeUSB.OnSpecifiedDeviceRemoved
                    += new System.EventHandler(singleton.mag_usb_OnSpecifiedDeviceRemoved);
                singleton.magSwipeUSB.OnDeviceArrived
                    += new System.EventHandler(singleton.mag_usb_OnDeviceArrived);
                singleton.magSwipeUSB.OnDeviceRemoved
                    += new System.EventHandler(singleton.mag_usb_OnDeviceRemoved);
                singleton.magSwipeUSB.OnDataRecieved
                    += new DataRecievedEventHandler(singleton.mag_usb_OnDataRecieved);
                singleton.magSwipeUSB.OnSpecifiedDeviceArrived
                    += new System.EventHandler(singleton.mag_usb_OnSpecifiedDeviceArrived);
                singleton.magSwipeUSB.OnDataSend +=
                    new System.EventHandler(singleton.mag_usb_OnDataSend);


                if (Constants.HasCoinDispenser)
                {
                    singleton.coinUSB = new UsbHidPort();
                    singleton.coinUSB.ProductId = 0;
                    singleton.coinUSB.VendorId = 5332;
                    singleton.coinUSB.OnSpecifiedDeviceRemoved
                        += new System.EventHandler(singleton.coin_usb_OnSpecifiedDeviceRemoved);
                    singleton.coinUSB.OnDeviceArrived
                        += new System.EventHandler(singleton.coin_usb_OnDeviceArrived);
                    singleton.coinUSB.OnDeviceRemoved
                        += new System.EventHandler(singleton.coin_usb_OnDeviceRemoved);
                    singleton.coinUSB.OnDataRecieved
                        += new DataRecievedEventHandler(singleton.coin_usb_OnDataRecieved);
                    singleton.coinUSB.OnSpecifiedDeviceArrived
                        += new System.EventHandler(singleton.coin_usb_OnSpecifiedDeviceArrived);
                    singleton.coinUSB.OnDataSend +=
                        new System.EventHandler(singleton.coin_usb_OnDataSend);
                }

                WindowInteropHelper helper = new WindowInteropHelper(this);
                magSwipeUSB.RegisterHandle(helper.Handle);

                if (Constants.HasCoinDispenser)
                {
                    coinUSB.RegisterHandle(helper.Handle);
                }

                HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
                if (source != null)
                {
                    source.AddHook(new HwndSourceHook(this.WndProc));
                }
                base.OnSourceInitialized(e);
            }
            catch (Exception ex)
            {
                App.HadUsbInitializationFailure = true;
                Logging.LogException(ex);
            }
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == Oceanside.Usb.Win32Usb.WmDeviceChanged)
            {
                try
                {
                    if (coinUSB != null)
                    {
                        coinUSB.ParseMessages(msg, wParam);
                    }
                    if (magSwipeUSB != null)
                    {
                        magSwipeUSB.ParseMessages(msg, wParam);
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                }
            }
            return hwnd;
        }

        /// <summary>
        /// Has to be here or we will cause exceptions later.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mag_usb_OnDeviceArrived(object sender, EventArgs e)
        {

        }
        private void coin_usb_OnDeviceArrived(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// Has to be here or we will cause exceptions later.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mag_usb_OnDeviceRemoved(object sender, EventArgs e)
        {

        }
        private void coin_usb_OnDeviceRemoved(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Event is fired if the device is removed from the USB Port
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mag_usb_OnSpecifiedDeviceRemoved(object sender, EventArgs e)
        {

        }
        private void coin_usb_OnSpecifiedDeviceRemoved(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// This event hanlder must be implemented it does nothing if null, or we will
        /// get an exception.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mag_usb_OnDataSend(object sender, EventArgs e)
        {

        }
        private void coin_usb_OnDataSend(object sender, EventArgs e)
        {

        }
        const int CONST_T1_LEN = 3;
        const int CONST_T2_LEN = 4;
        const int CONST_T3_LEN = 5;
        const int CONST_DATA_START = 10;

        /// <summary>
        /// This is an event handler that will fire every time a byte is 
        /// recieved by this software.  The bytes are inbound from the
        /// USB target and device ID that we registered for.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void mag_usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            try
            {
                byte t1Len = args.Data[CONST_T1_LEN];
                byte t2Len = args.Data[CONST_T2_LEN];
                byte t3Len = args.Data[CONST_T3_LEN];

                int totalValidDataSize = t1Len + t2Len + t3Len;
                byte[] bytes = new byte[totalValidDataSize];
                for (int bIndx = CONST_DATA_START; bIndx < (totalValidDataSize + CONST_DATA_START); bIndx++)
                {
                    bytes[bIndx - CONST_DATA_START] = args.Data[bIndx];
                }

                string magString = _enc.GetString(bytes);
                if (!String.IsNullOrEmpty(magString))
                {
                    if (magString.Contains(Constants.MagCardLoginToken))
                    {
                        PosWindow.MainPosWindow.Dispatcher.BeginInvoke(new Action(() => MagCardDelegates.PosLoginCardSwiped(magString)));
                    }
                    else
                    {
                        PosWindow.MainPosWindow.Dispatcher.BeginInvoke(new Action(() => MagCardDelegates.PaymentCardSwiped(magString)));
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
        }
        private void coin_usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            try
            {
                byte statusByte = args.Data[1];

                if (statusByte == 0x02)
                {
                    ///This will be the reset machine status, ignore it.
                }
                else
                { 
                  ///Otherwise this is the status byte for dispense by amount.
                    bool dispensed = (statusByte & 0x20) == 0x20;
                    if (!dispensed)
                    {
                        UMD.ShowGuiMessageSTASafe_NOTHROW("The system was unable to dispense the customer's coins.");
                    }
                }

            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
        }
        #endregion
    }
}
